var entity = require('../entity');
var Order = entity.Order;



exports.newAndSave = function(params, callback){
    var order = new Order();
    order.creator = params.creatorId;
    order.faction = params.factionId;
    order.tradeNo = params.tradeNo;
    order.totalFee = params.totalFee;
    order.status = 'waiting';
    order.remark = '';
    order.address = params.address;
    order.goodsList = [];
    params.goods.forEach(function(goods){
        order.goodsList.push(goods);
    })
    if(params.wxpayResult){
        order.wxpayResult = params.wxpayResult
    }
    if(params.payResult){
        order.payResult = params.payResult
    }
    order.save(function(err, order){
        callback(err, order);
    });
}

exports.addAddress = function(id, address, callback){
    Order.update({_id: id}, {address: address}, {}, function(err, resp){
        callback(err, resp);
    })
}

exports.setWaiting = function(id, callback){
    Order.update({_id: id}, {status: 'waiting'}, {}, function(err, resp){
        callback(err, resp);
    })
}

exports.setPay = function(id, callback){
    Order.update({_id: id}, {status: 'pay'}, {}, function(err, resp){
        callback(err, resp);
    })
}
exports.setFinish = function(id, callback){
    Order.update({_id: id}, {status: 'finish'}, {}, function(err, resp){
        callback(err, resp);
    })
}
exports.updateOrderStatus = function(tradeNo, params, callback){
    Order.update({tradeNo: tradeNo}, {
        remark: params.remark,
        status: params.status,
        wxpayResult: params.wxpayResult
    }, {}, function(err, resp){
        callback(err, resp)
    })
}

exports.findByFactionAndStatus = function(factionId, status, callback){
    var params = {
        faction: factionId
    }
    if(status)
        params.status = status;
    Order.find(params).populate('creator')
        .exec(function(err, orders){
            callback(err, orders);
        })
}

exports.findOrderByUserAndStatus = function(userId, status, callback){
    Order.find({creator: userId, status: status})
        .populate('creator').populate('faction')
        .exec(function(err, resp){
        callback(err, resp);
    })
}

exports.findById = function(id, callback){
    Order.findOne({_id: id}).populate('creator').exec(function(err, order){
        callback(err, order);
    })
}

exports.removeOrder = function(id, callback){
    Order.remove({_id: id}, function(err, resp){
        callback(err, resp);
    })
}



